//mysql连接池配置文件
const mysql = require("mysql");
const path = require("path")
const $dbConfig = require("./dbConfig"); //注意改成自己项目中mysql配置文件的路径
const sql = require("./sql.js"); //sql语句封装
const db1 = mysql.createPool($dbConfig.db1); // 使用连接池，避免开太多的线程，提升性能
const json = require("./json");
const config = require('../data/config.js')
const configPath = config.configPath
const { dingdingSend } = require("../db/dingding.js");
const crypto = require("crypto");
const jwt = require("jsonwebtoken");
const Salt = require("../data/Salt.json");
const {
  executeCommand,
  appStatus,
  startProcess,
  stopProcess,
} = require("../db/exe.js");
const {
  readDocument,
  asyncReadDocument,
  writeDocument,
  asyncWriteDocument,
  readini,
  writeini,
  deleteFile,
  asyncDeleteFile,
  createFolder,
  createFile,
  checkPath,
  isFileOrFolder,
} = require("./operFile.js"); 




// 执行命令
async function runCommand() {
  try {
    // 钉钉发消息
    dingdingSend("测试发送钉钉消息");
    // 启动程序 C:\\Users\\Administrator\\Desktop\\GUI多线程.exe
    startProcess("C:\\Users\\Administrator\\Desktop\\GUI多线程.exe");
    // 查看进程状态，返回 ["subprocess子进程.exe", "22936", "Console", "1", "5,564", "K\r"]
    let lists = await appStatus("GUI多线程.exe");
    console.log(`获取的程序状态：`, lists);
    // 在 5 秒后停止程序
    setTimeout(async () => {
      let res = await stopProcess("GUI多线程.exe");
      console.log(`返回终止程序结果：${res}`);
    }, 5000);
  } catch (error) {
    console.log("执行命令失败",error);
  }
}
// runCommand();


//将前端传输过来的key解压成盐(与前端加盐对应)
function jiexi(key) {
  function is0(data) {
    if (data == 0) {
      return 0
    } else {
      return data
    }
  }
  var randomString = key.slice(0, -11)
  var randomnumber = key.slice(-11,)
  var mmm = ''
  for (var i = 0; i < randomnumber.length; i++) {
    mmm += randomString[randomnumber[is0(i)]];
  }
  return mmm
}


// sha256加密密码并验证,getpassword为前端传过来的密码
function verifyPassword(password, getpassword) {
  const hashedPassword = crypto
    .createHash('sha256')
    .update(password)
    .digest('hex');
  // 验证密码是否匹配
  if (hashedPassword === getpassword) {
    return true; // 密码正确
  } else {
    return false; // 密码错误
  }
}
// 验证用户是否存在
function verifyUser(account) {
  return new Promise((resolve, reject) => {
    var pool = db1;
    var sqlString = `select * from sys_user where NserName =?`;
    pool.getConnection((err, connection) => {
      if (err) {
        reject(err);
      } else {
        connection.query(sqlString, [account], (err, result) => {
          connection.release(); // 释放连接
          if (err) {
            reject(false);
          } else {
            resolve(result); // 返回 result
          }
        });
      }
    });
  });
}

/**
 * @description 新增一条数据
 * @param  {str} table 数据库表的名称
 * @param  {obj} req 插入的数据
 * @param  {obj} res 接口函数中的res对象
 * @param  {obj} next 接口函数中的next对象
 */

// 登录操作
let login = (table, req, res) => {
  let ip = req.ip;
  ip = ip.replace(/^.*:(.*)$/, "$1");
  let { account, password, key } = req.body;
  key = jiexi(key);
  let status = 1
  let msg = ''
  let config = readini(configPath);
  if (config.code == 200) {
    config = config.data.config;
  } else {
    // 没有配置文件的话默认账号密码
    config = {
      user: "admin",
      password: "admin123",
      permission: "administrator",
    };
  }
  if (account != config.user) {
    msg = "账号错误";
    status = 0;
    return res.json({
      code: 300,
      msg: msg,
      data: [],
    });
  }
  let UserPassword = crypto
    .createHash("md5")
    .update(config.password)
    .digest("hex");
  //验证密码是否正确
  let yanzheng = verifyPassword(UserPassword + key, password);

  if (yanzheng) {
    const Permission = config.permission;
    const userdata = {
      account: account,
      Permission: Permission,
    };
    let token = jwt.sign(userdata, Salt.Salt, {
      expiresIn: 30 * 60,
    });
    // let avatar = result[0].avatar.toString("base64") ;
    const data = {
      User: account,
      Account: account,
      Permission: Permission,
    };
    // 以json形式，把操作结果返回给前台页面
    msg = '登录成功'
    res.json({
      code: 200,
      msg: msg,
      data: data,
      token: token,
    });
  } else {
    msg = "密码错误";
    status = 0;
    res.json({
      code: 300,
      msg: msg,
      data: [],
    });
  }
  const params = [account, ip, status, msg];
  // setLoginLog(params)
  var pool = db1;
  // pool.getConnection((err, connection) => {
  //   if (!err) {
  //     connection.query(sql[table].login, [account], (err, result) => {
  //       let msg = "登录成功";
  //       let status = 0;
  //       if (err) {
  //         console.log(err);
  //         msg = "操作失败";
  //         status = 1;
  //         res.json({
  //           code: "300",
  //           msg: "操作失败:",
  //         });
  //       } else {
  //         console.log(119, result.avatar);
  //         if (result != "") {
  //           //验证密码是否正确
  //           let yanzheng = verifyPassword(
  //             result[0].UserPassword + key,
  //             password
  //           );

  //           if (yanzheng) {
  //             const Permission = result[0].Permission;
  //             const userdata = {
  //               account: account,
  //               Permission: Permission,
  //             };
  //             let token = jwt.sign(userdata, Salt.Salt, {
  //               expiresIn: 120 * 60,
  //             });
  //             // let avatar = result[0].avatar.toString("base64") ;
  //             const data = {
  //               User: result[0].Name,
  //               Account: account,
  //               Permission: Permission,
  //               Email: result[0].email,
  //               JobNumber: result[0].JobNumber,
  //               Role: result[0].role,
  //               avatar: result[0].avatar,
  //             };
  //             console.log(144, data);
  //             // 以json形式，把操作结果返回给前台页面
  //             res.json({
  //               code: 200,
  //               msg: msg,
  //               data: data,
  //               token: token,
  //             });
  //           } else {
  //             msg = "密码错误";
  //             status = 1;
  //             res.json({
  //               code: 300,
  //               msg: msg,
  //               data: [],
  //             });
  //           }
  //         } else {
  //           msg = "用户不存在";
  //           status = 1;
  //           res.json({
  //             code: 300,
  //             msg: msg,
  //             data: [],
  //           });
  //         }
  //       }
  //       const params = [account, ip, status, msg];
  //       // setLoginLog(params)
  //       connection.release();
  //     });
  //   } else {
  //     console.log(err);
  //     json(res, "444", err);
  //   }
  // });
};
// 修改密码;
let updatepwd = (table, req, res) => {
  let { old_pwd, new_pwd, account } = req.body;
  console.log(283, old_pwd, new_pwd, account);
  let result = readini(configPath);
  console.log(285, result)
  if (result.code == 200) {
    let data = result.data
    let UserPassword = crypto.createHash("md5").update(data.config.password).digest("hex");
    if (UserPassword == old_pwd) {
      data.config.password = new_pwd;
      writeini(data)
      return res.json({code:200,msg:'更改密码成功'})
    } else {
      return res.json({ code: 300, msg: "原密码不正确" });
    }
  }
  return res.json({ code: 300, msg: "更改密码失败" });
};
let getUser = (table, database, res) => {
  var pool = db1;
  pool.getConnection((err, connection) => {
    if (!err) {
      connection.query(sql[table].getUser, (err, result) => {
        if (err) {
          console.log(err);
          res.json({
            code: "300",
            msg: "操作失败:",
          });
        } else {
          console.log("打印结果", result);
          res.json({
            code: "200",
            msg: "操作成功:",
            data: result,
          });
        }
        connection.release();
      });
    } else {
      console.log(err);
      console.log("database connect fault");
    }
  });
};
// 获取配置信息
let getConfig = (req,res) => {
  let result = readini(configPath);
  // 转换格式
  function transformToStructure(inputData) {
    // 用来存储最终结果
    const result = [];

    // 递归处理每个对象
    function processNode(obj, parentKey) {
      return Object.keys(obj).map((key) => {
        const value = obj[key];
        const currentKey = parentKey ? `${parentKey}-${key}` : key;

        // 判断当前值是否为对象，如果是，则递归转换成子项
        const node = {
          name: key,
          value:
            typeof value === "object" && !Array.isArray(value) ? "" : value,
          key: currentKey,
        };

        if (typeof value === "object" && !Array.isArray(value)) {
          node.children = processNode(value, currentKey); // 递归子节点
        }

        return node;
      });
    }

    // 遍历原始数据的每个键
    for (const [key, value] of Object.entries(inputData)) {
      const node = {
        name: key,
        value: "",
        key: key,
        children: processNode(value, key),
      };
      result.push(node);
    }

    return result;
  }
  if (result.code == 200) {
    let config = transformToStructure(result.data);
    res.json({
      code: 200,
      msg:'读取配置成功',
      data: config,
    });
  } else {
    res.json({
      code: 300,
      msg: "读取配置失败",
      data: config,
    });
  }
  
}
// 获取按钮信息memoryUsage
let getButton = (req, res) => {
  let result = readini(configPath);
  if (result.code == 200) {
    if ("button" in result.data) {
      let config = result.data.button;
      // 遍历 JSON 对象并根据 appPath 获取文件名
      for (const key in config) {
        if (config.hasOwnProperty(key)) {
          const appPath = config[key].appPath;
          const app = path.basename(appPath); // 获取文件名
          config[key].app = app; // 将文件名添加到对应的对象中
        }
      }
      return res.json({ code: 200, msg: "获取按钮信息成功", data: config });
    } 
  } 
  res.json({
    code: 300,
    msg: "获取按钮信息失败",
    data:[]
  });
  
};
// 获取app日志
let getAppLog = (req, res) => {
  const appLog = req.body.appLog
  let result = readDocument(appLog);
  if (result.code == 200) {
    let data = result.data;
    // 转换后的结果
    const formattedLogs = data
      .filter((item) => item !== "")
      .map((item) => {
        const [timePart, ...logParts] = item.split(" - ");
        const time = timePart.split(",")[0]; // 获取时间部分，不包含毫秒
        const log = logParts.join(" - "); // 将日志内容拼接在一起
        return {
          time: time,
          log: log,
        };
      });
    return res.json({ code: 200, msg: "获取app日志成功", data: formattedLogs });
  }
  res.json({
    code: 300,
    msg: "获取app日志失败",
    data: [],
  });
};
// 获取app状态
let getAppStatus = async (req, res) => {
  const app = req.body.app;
  let result = await appStatus(app);
  if (result.length>0) {
    // 转换为对象数组
    const outputArray = result.map((item) => ({
      imageName: item[0],
      PID: item[1],
      sessionName: item[2],
      sessionId: item[3],
      memoryUsage: item[4] + " " + item[5].trim(), // 拼接内存使用值并去掉回车符
    }));
    return res.json({ code: 200, msg: "app正在运行", data: outputArray });
  }
  res.json({
    code: 300,
    msg: "app没有运行",
    data: [],
  });
};
// 开启app
let startApp = async (req, res) => {
  const appPath = req.body.appPath;
  const fileName = path.basename(appPath);
  console.log(450, appPath, fileName);
  let result1 = await appStatus(fileName);
  console.log(452,result1)
  if (result1.length == 0) { 
    await startProcess(appPath);
    return res.json({code:200,msg:'程序启动完成'})
  } else {
    return res.json({ code: 300, msg: "程序已启动,请勿重复开启" });
  }
};
// 停止app
let stopApp = async (req, res) => {
  const appPath = req.body.appPath;
  const fileName = path.basename(appPath);
  console.log(464, appPath, fileName);
  let result = await stopProcess(fileName);
  if(result){
    return res.json({ code: 200, msg: "程序关闭操作完成" });
  } else {
    return res.json({ code: 300, msg: "程序关闭操作失败" });
  }
};

// 更新配置信息
let updateConfig = (req, res) => {
  let config = req.body.config
  // 转换格式
  function reverseTransformToObject(inputData) {
    // 递归处理每个节点
    function processNode(node) {
      const result = {};

      node.forEach((item) => {
        if (item.children && item.children.length > 0) {
          // 如果有子节点，递归转换
          result[item.name] = processNode(item.children);
        } else {
          // 如果没有子节点，直接赋值
          result[item.name] = item.value;
        }
      });

      return result;
    }

    // 执行逆向转换
    return processNode(inputData);
  }
  config = reverseTransformToObject(config);
  let result = writeini(configPath,config);
  res.json(result)
}
// 测试
let test = async(req, res) => {
  const filePath = "C:/Users/Administrator/Desktop/logs/app.log"; // 替换为你的 .log 文件路径
  const filePath2 = "C:/Users/Administrator/Desktop/logs/app.txt"; // 替换为你的 .log 文件路径
  let bbb = readDocument(filePath);
  // console.log("文件内容:", bbb);
  if (bbb.code == 200) {
    bbb.data.forEach((item) => {});
  }
  let config = readini(configPath);
  if (config.code == 200) {
    let config2 = config.data;
    config2["config"] = {name:"李思文"}
    // console.log(98, config2);

    // writeini("./config2.ini", config2);
  }
  // dingdingSend('哈哈哈哈哈')
  // writeDocument("./app.txt",['DFDS',123,'舒服舒服']);
  // let ccc = await asyncWriteDocument("./app.txt", ["erer", 455, "道德风尚"]);
  // console.log(113, ccc)
  // let ddd = await asyncDeleteFile("./app.txt");
  // console.log(118,ddd)
  // let fff = deleteFile('./app.txt')
  // console.log(120, fff);
  // createFolder('./abc.log')
  // console.log(120,isFileOrFolder("./abcd"));
  // let hhh = createFolder("./abc.log");
  // console.log(125, hhh)
  res.json({
    code: 200,
  });
};

module.exports = {
  login,
  updatepwd,
  getButton,
  getAppLog,
  getAppStatus,
  startApp,
  stopApp,
  getUser,
  getConfig,
  updateConfig,
  test,
};
